module(..., package.seeall)
--local fd_buf = require('fd_buffer')

local function show_debug_info(info)
	print('source:', info.source)
	print('what:', info.what)
	print('func:', info.func)
	print('nups:', info.nups)
	print('short_src:', info.short_src)
	print('name:', info.name)
	print('currentline:', info.currentline)
	print('namewhat:', info.namewhat)
	print('linedefined:', info.linedefined)
	print('lastlinedefined:', info.lastlinedefined)
end

local loger_level = {DEBUG = 1, TRACE = 2, INFO = 3, WARN = 4, ERROR = 5, debug = 1, trace = 2, info = 3, warn = 4, error = 5}

function new(level, fd, out)
	local buf = nil
	--[[
	if fd and (fd > 0) then
		buf = fd_buf.new(fd, fd_buf.FD_BUFFER_WRITE)
		if not buf then
			return nil, 'fd_buffer new fail'
		end
	end
	]]

	local self = {buf = buf, level = level, out = out}
	local obj = {}

	function obj.set_out(out)
		self.out = out
	end

	function obj.set_level(level)
		self.level = level
	end

	function obj.get_level()
		return self.level
	end

	function obj.log(level, str)
		local d_info = debug.getinfo(3, 'nl')
		d_info.name = d_info.name or 'main'
		local d_str = string.format('[%s()-%s: %s] %s\n', d_info.name, d_info.currentline, level, str)
		if self.out > 0 then
			--show_debug_info(d_info)
			io.write(d_str)
		end

		if self.buf then
			self.buf:write(d_str)
		end
	end

	function obj.debug(fmt, ...)
		if loger_level[self.level] <= loger_level['DEBUG'] then
			return obj.log('DEBUG', string.format(fmt, ...))
		end
	end

	function obj.trace(fmt, ...)
		if loger_level[self.level] <= loger_level['TRACE'] then
			return obj.log('TRACE', string.format(fmt, ...))
		end
	end

	function obj.info(fmt, ...)
		if loger_level[self.level] <= loger_level['INFO'] then
			return obj.log('INFO', string.format(fmt, ...))
		end
	end

	function obj.warn(fmt, ...)
		if loger_level[self.level] <= loger_level['WARN'] then
			return obj.log('WARN', string.format(fmt, ...))
		end
	end

	function obj.error(fmt, ...)
		if loger_level[self.level] <= loger_level['ERROR'] then
			return obj.log('ERROR', string.format(fmt, ...))
		end
	end

	return obj

end

--return _G[modname]
return _M
